#include "sdk.h"
#include "editarraystringdlg.h"

BEGIN_EVENT_TABLE( EditArrayStringDlg, wxScrollingDialog )
  EVT_LISTBOX_DCLICK( XRCID( "lstItems" ), EditArrayStringDlg::OnEdit )
  EVT_BUTTON( XRCID( "btnAdd" ), EditArrayStringDlg::OnAdd )
  EVT_BUTTON( XRCID( "btnEdit" ), EditArrayStringDlg::OnEdit )
  EVT_BUTTON( XRCID( "btnDelete" ), EditArrayStringDlg::OnDelete )
  EVT_UPDATE_UI( -1, EditArrayStringDlg::OnUpdateUI )
END_EVENT_TABLE()

EditArrayStringDlg::EditArrayStringDlg( wxWindow* parent, wxArrayString& array ) : m_Array( array ) {
  wxXmlResource* xml_res = wxXmlResource::Get();
  wxString resPath = ConfigManager::GetDataFolder() + _T( "/edit_array_string.xrc" );
  xml_res->Load( resPath );
  if( !xml_res->LoadObject( this, parent, _T( "dlgEditArrayString" ), _T( "wxScrollingDialog" ) ) ) {
    return;
  }
  XRCCTRL( *this, "wxID_OK", wxButton )->SetDefault();
  wxListBox* list = XRCCTRL( *this, "lstItems", wxListBox );
  list->Clear();
  for( unsigned int i = 0; i < m_Array.GetCount(); ++i ) {
    list->Append( m_Array[i] );
  }
}

EditArrayStringDlg::~EditArrayStringDlg() {
}

void EditArrayStringDlg::EndModal( int retCode ) {
  if( retCode == wxID_OK ) {
    wxListBox* list = XRCCTRL( *this, "lstItems", wxListBox );
    m_Array.Clear();
    for( int i = 0; i < ( int )list->GetCount(); ++i ) {
      m_Array.Add( list->GetString( i ) );
    }
  }
  wxScrollingDialog::EndModal( retCode );
}

void EditArrayStringDlg::OnAdd( wxCommandEvent& ( event ) ) {
  wxString w = cbGetTextFromUser( _T( "Add item" ), _T( "Enter the new item:" ) );
  if( !w.IsEmpty() ) {
    XRCCTRL( *this, "lstItems", wxListBox )->Append( w );
  }
}

void EditArrayStringDlg::OnEdit( wxCommandEvent& ( event ) ) {
  wxListBox* list = XRCCTRL( *this, "lstItems", wxListBox );
  wxString w = list->GetStringSelection();
  w = cbGetTextFromUser( _T( "Edit item" ), _T( "Edit the item:" ), w );
  if( !w.IsEmpty() ) {
    list->SetString( list->GetSelection(), w );
  }
}

void EditArrayStringDlg::OnDelete( wxCommandEvent& ( event ) ) {
  if( msging( _T( "Delete this item?" ), _T( "Confirm" ), wxYES_NO ) == wxID_YES ) {
    wxListBox* list = XRCCTRL( *this, "lstItems", wxListBox );
    list->Delete( list->GetSelection() );
  }
}

void EditArrayStringDlg::OnUpdateUI( wxUpdateUIEvent& ( event ) ) {
  const bool en = XRCCTRL( *this, "lstItems", wxListBox )->GetSelection() != -1;
  XRCCTRL( *this, "btnEdit", wxButton )->Enable( en );
  XRCCTRL( *this, "btnDelete", wxButton )->Enable( en );
}
